<?php


namespace App\Http\Admin\Controllers\V1\AdminUser;


use App\Http\Admin\Controllers\V1\BasisController;
use App\Libs\Common\Cache\PermissionMenu;
use App\Models\AdminGroup;
use App\Models\AdminMenu;
use Illuminate\Support\Facades\DB;

class GroupController extends BasisController
{
    protected $modelGroup;
    public function __construct()
    {
        parent::__construct();
        $this->modelGroup = new AdminGroup();
    }

    public function lists(){
        $conditions = [
            'keyword' => request('keyword'),
            'name' => request('name'),
            'status' => request('status'),
            'start_time' => request('start_time'),
            'end_time' => request('end_time'),
        ];
        $page = request('page',1);
        $pageSize = request('page_size',20);
        $orderArr=[];
        $orderArr[] = array('field'=>'admin_group.list_order','direction'=>'asc');
        $lists = $this->modelGroup->paginateLists($conditions,[],$orderArr,$page,$pageSize);

        foreach ($lists as $key=>$val){
            $lists[$key]->admin_num = DB::table('admin_group_access')->where('group_id',$val->id)->count();
        }

        $statusArray = $this->modelGroup->statusArray();
        return $this->view(compact(array('lists','statusArray')),'admin_user/group/lists');
    }

    public function create(){
        if(request()->isMethod('post')) {
            $this->validate(request(), $this->modelGroup->rules, $this->modelGroup->messages);
            $groupName = trim(request('name'));
            $description = trim(request('description'));
            $list_order = trim(request('list_order',999));
            $status = trim(request('status'));
            $menus = request('menus');
            if($this->modelGroup->where('name',$groupName)->value('id')){
                return $this->responseMsg('210000',false,"角色名称已存在");
            }
            if(empty($menus)){
                return $this->responseMsg('210010',false,"请选择权限");
            }
            DB::beginTransaction();
            try{
                // 添加角色组
                $insertGroupId = DB::table('admin_group')->insertGetId([
                    'name' => $groupName,
                    'description' => $description,
                    'list_order' => $list_order,
                    'status' => $status,
                    'updated_user' => $this->adminUser->id,
                ]);
                $menusIds = explode(',',$menus);
                $insertGroupMenuData = [];
                foreach ($menusIds as $key=>$val){
                    if($val){
                        $insertGroupMenuData[] = array(
                            'group_id' => $insertGroupId,
                            'menu_id' => $val,
                        );
                    }
                }
                $insertGroupMenu = false;
                if($insertGroupMenuData){
                    $insertGroupMenu = DB::table('admin_group_menu')->insert($insertGroupMenuData);
                }
                if($insertGroupId && $insertGroupMenu){
                    DB::commit();
                    PermissionMenu::getCleanUpAllMenu();        // 清理管理员权限菜单缓存
                    return $this->responseMsg('000000',true,'创建成功',array('url'=>'/admin/v1/admin_user/group/lists'));
                }
            }catch (\Exception $e){
                DB::rollBack();
                return $this->responseMsg('200000',false,"Error:: {$e->getMessage()}");
            }
            return $this->responseMsg('200000',false,"创建失败");
        }

        $statusArray = $this->modelGroup->statusArray();
        $groupMenu = $this->groupMenu();
        return $this->view(array('statusArray'=>$statusArray,'menus'=>$groupMenu['menus']),'admin_user/group/create');
    }

    public function edit(){
        $groupId = request('id');
        if(request()->isMethod('post')) {
            $this->validate(request(), $this->modelGroup->rules, $this->modelGroup->messages);
            $groupName = trim(request('name'));
            $description = trim(request('description'));
            $list_order = trim(request('list_order',999));
            $status = trim(request('status'));
            $menus = request('menus');
            if(empty($menus)){
                return $this->responseMsg('210010',false,"请选择权限");
            }
            $beforeId = $this->modelGroup->where([
                ['name','=',$groupName],
                ['id','<>',$groupId],
            ])->value('id');
            if($beforeId){
                return $this->responseMsg('210000',false,"角色名称已存在");
            }

            $groupData = $this->modelGroup->find($groupId);

            $updateData = [];
            $updateData['updated_at'] = date('Y-m-d H:i:s');
            if($groupData->name != $groupName){
                $updateData['name'] = $groupName;
            }
            if($groupData->description != $description){
                $updateData['description'] = $description;
            }
            if($groupData->list_order != $list_order){
                $updateData['list_order'] = $list_order;
            }
            if($groupData->status != $status){
                $updateData['status'] = $status;
            }
            if($groupData->updated_user != $this->adminUser->id){
                $updateData['updated_user'] = $this->adminUser->id;
            }

            DB::beginTransaction();
            try{
                // 更新角色组
                $updateGroup = true;
                if($updateData){
                    $updateGroup = DB::table('admin_group')->where('id',$groupId)->update($updateData);
                }
                $menusIds = explode(',',$menus);

                $insertGroupMenuData = [];
                foreach ($menusIds as $key=>$val){
                    if($val){
                        $insertGroupMenuData[] = array(
                            'group_id' => $groupId,
                            'menu_id' => $val,
                        );
                    }
                }

                $insertGroupMenu = true;
                $delGroupMenu = DB::table('admin_group_menu')->where('group_id',$groupId)->delete();
                if($insertGroupMenuData){
                    $insertGroupMenu = DB::table('admin_group_menu')->insert($insertGroupMenuData);
                }
                if($updateGroup && $insertGroupMenu){
                    DB::commit();
                    PermissionMenu::getCleanUpAllMenu();        // 清理管理员权限菜单缓存
                    return $this->responseMsg('000000',true,'更新成功',array('url'=>'/admin/v1/admin_user/group/lists'));
                }
            }catch (\Exception $e){
                DB::rollBack();
                return $this->responseMsg('200000',false,"Error:: {$e->getMessage()}",array('wait'=>200));
            }
            return $this->responseMsg('200000',false,"更新失败");
        }
        $statusArray = $this->modelGroup->statusArray();
        $groupMenu = $this->groupMenu($groupId);
        return $this->view(array('statusArray'=>$statusArray,'info'=>$groupMenu['group'],'menus'=>$groupMenu['menus']),'admin_user/group/edit');
    }

    public function info(){
        $groupId = request('id');
        $statusArray = $this->modelGroup->statusArray();
        $groupMenu = $this->groupMenu($groupId);
        return $this->view(array('statusArray'=>$statusArray,'info'=>$groupMenu['group'],'menus'=>$groupMenu['menus']),'admin_user/group/info');
    }

    public function del(){
        $groupId = request('id');
        DB::beginTransaction();
        try{
            $groupAllMenu = $this->modelGroup->groupMenuIds($groupId);
            if($groupAllMenu){
                $delMenu = DB::table('admin_group_menu')->where('group_id',$groupId)->delete();
            }else{
                $delMenu = true;
            }
            $delGroup = DB::table('admin_group')->where('id',$groupId)->delete();
            if($delGroup && $delMenu){
                DB::commit();
                PermissionMenu::getCleanUpAllMenu();        // 清理管理员权限菜单缓存
                return $this->responseMsg('000000',true,'删除成功');
            }
        }catch (\Exception $e){
            DB::rollBack();
            return $this->responseMsg('200000',false,"Error:: {$e->getMessage()}",array('wait'=>200));
        }
        return $this->responseMsg('200000',false,"删除失败");
    }

    private function groupMenu($groupId=0)
    {
        $modelMenu = new AdminMenu();
        $where = [];
        $where[] = ['is_display','=',1];
        $menuLists = $modelMenu->getMenuList($where);
        $groupData = (object)[];
        $menusIds = [];
        if($groupId){
            $groupData = $this->modelGroup->find($groupId);
            $menusIds = $this->modelGroup->groupMenuIds($groupId);
        }
        foreach ($menuLists as $k => $v) {
            $menus[$k] = ['id' => $v['id'], 'pId' => $v['parent_id'], 'name' => $v['menu_name'], 'open' => true];
            if (in_array($v['id'], $menusIds)) {
                $menus[$k]['checked'] = true;
            }
        }
        return array(
            'group' => $groupData,
            'menus' => $menus,
        );
    }

}
